package com.hntx.joymusic.record;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hntx.joymusic.R;
import com.hntx.joymusic.mediaplayer.IMPlayListener;
import com.hntx.joymusic.mediaplayer.MPlayer;
import com.hntx.joymusic.mediaplayer.StringUtils;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import static android.view.Gravity.BOTTOM;
import static android.view.Gravity.CENTER;

public class RecordPlayer extends Activity implements
        SeekBar.OnSeekBarChangeListener,
        MPlayer.OnVideoChangedListener,
        MPlayer.IMInfoListener {

    private SurfaceView mPlayerView;
    private MPlayer player;
    private static final int HIDE = 1, SHOW = 2, ENABLE_SEEK = 4;
    private int timeout = 5000;
    private int videoDuration;

    private Timer timer;
    private TimerTask timerTask;
    private Handler mHandler = new MyHandler(this);
    public final String TAG = "RecordPlayerLog";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getIntentData();
    }

    private void getIntentData() {
        setContentView(R.layout.record_player_layout);
        path = getIntent().getStringExtra("path");
        initView();
        initData();
        initPlayer();
    }

    RelativeLayout recordBottomLayout, updateProgressBar;
    private SeekBar seekBar;
    private TextView tv_time_total, tv_time_current;
    private ImageView load_img;
    private ImageButton btn_play_pause;

    private void initView() {
        recordBottomLayout = findViewById(R.id.record_bottom_layout);
        seekBar = findViewById(R.id.record_seekbar);
        updateProgressBar = findViewById(R.id.update_progress);
        mPlayerView = findViewById(R.id.mPlayerView);
        btn_play_pause = findViewById(R.id.btn_play_pause);
        tv_time_total = findViewById(R.id.tv_time_total);
        tv_time_current = findViewById(R.id.tv_time_current);
        load_img = findViewById(R.id.load_img);
        seekBar.setOnSeekBarChangeListener(this);
    }

    private void initData() {
        Animation translateAnimation = AnimationUtils.loadAnimation(this, R.anim.load_anim);
        if (load_img != null) {
            load_img.setAnimation(translateAnimation);
            load_img.startAnimation(translateAnimation);
        }
    }

    private String path = null;

    private void initPlayer() {
        player = new MPlayer();
//        player.setDisplay(mPlayerView);
        player.setOnVideoChangedListener(this);
        player.setMediaInfoListener(this);
        playerOnPrepared();
        playerSetListen();
        playerSurfaceDestroyed();
        playerOnBufferUpdateListen();
        seedCompletedListen();
        if (!TextUtils.isEmpty(path)) {
            starPlayUrl(path);
        }
    }

    private void starPlayUrl(String mUrl) {
        if (!TextUtils.isEmpty(mUrl)) {
            if (mUrl.length() > 0) {

                try {
                    player.setSource(mUrl);
                    player.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean isTimerTask = false;

    private void playerOnPrepared() {
        player.setOnPrepared(() -> {
            mHandler.sendMessageDelayed(mHandler.obtainMessage(ENABLE_SEEK), timeout);
            videoDuration = player.getDuration();
            seekBar.setMax(videoDuration);
            seekBar.setProgress(player.getCurrentPosition());
            String time = StringUtils.generateTime(videoDuration);
            tv_time_current.setText("00:00");
//            mPlayerView.setBackgroundResource(R.drawable.mine);
            tv_time_total.setText(" / " + time);
//            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
            mHandler.sendEmptyMessage(HIDE);
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isTimerTask) {
                        if (timer != null)
                            timer.cancel();
                    }
                    if (player != null) {
                        final int currentPosition = player.getCurrentPosition();
                        seekBar.setProgress(currentPosition);
                        runOnUiThread(() -> {
                            String time1 = StringUtils.generateTime(currentPosition);
                            tv_time_current.setText(time1);
                        });
                    }
                }
            };
            timer.schedule(timerTask, 0, 100);
        });
    }

    private void playerSetListen() {
        player.setPlayListener(new IMPlayListener() {
            @Override
            public void onStart(MPlayer player) {
            }

            @Override
            public void onPause(MPlayer player) {
            }

            @Override
            public void onResume(MPlayer player) {
            }

            @Override
            public void onComplete(MPlayer player) {
                exit();
            }

            @Override
            public void onError(String source, int what, int extra) {
                Log.d(TAG, "视频播放出错，原因：" + what + "=" + source);
            }
        });
    }

    private void playerSurfaceDestroyed() {
        player.setiSurfaceDestroyed(() -> mHandler.removeCallbacksAndMessages(null));
    }

    private void playerOnBufferUpdateListen() {
        player.setImPlayerBufferUpdate((percent) ->
                runOnUiThread(() -> {
                    if (videoDuration > 0) {
                        seekBar.setSecondaryProgress((int) ((percent / 100.0) * videoDuration));
                    }
                })
        );
    }

    private void seedCompletedListen() {
        player.setiSeekCompleted(() -> hideBottomLayout());
    }

    private void hideBottomLayout() {
        if (recordBottomLayout.getVisibility() == View.VISIBLE) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void OnVideoChanged(boolean flag) {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = CENTER | BOTTOM;
        if (flag) {
            params.setMargins(0, 0, 0, 10);
        } else {
            params.setMargins(0, 0, 0, 100);
        }
    }

    @Override
    public boolean onMediaInfo(MediaPlayer mediaPlayer, int arg1, int arg2) {
        switch (arg1) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                //开始缓存，暂停播放
                updateProgressBar.setVisibility(View.VISIBLE);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                //缓存完成，继续播放
                if (player.isPlaying())
                    updateProgressBar.setVisibility(View.GONE);
                break;
        }
        return true;
    }

    private long mExitTime;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getAction()) {
            case KeyEvent.ACTION_DOWN:
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_ENTER:
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                        mHandler.sendEmptyMessage(SHOW);
                        View view = getCurrentFocus();
                        if (updateProgressBar != null && updateProgressBar.getVisibility() == View.VISIBLE) {
                            updateProgressBar.setVisibility(View.GONE);
                        }
                        if (view == null || view.getId() == R.id.seekBar || view.getId() == R.id.btn_play_pause) {
                            if (player != null) {
                                if (player.isPlaying()) {
                                    player.onPause();
                                    btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
                                    btn_play_pause.setVisibility(View.VISIBLE);
                                } else {
                                    try {
                                        player.onResume();
                                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
                                        mHandler.removeCallbacksAndMessages(null);
                                        mHandler.sendEmptyMessage(HIDE);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessage(HIDE);
                        if (recordBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewRight = getCurrentFocus();
                            if (focusViewRight != null)
                                if (focusViewRight.getId() == R.id.seekBar) {
                                    if (player != null) {
                                        player.seekto(player.getCurrentPosition() + 60000);
                                    }
                                    return true;
                                }
                        } else {
                            if (player != null) {
                                player.seekto(player.getCurrentPosition() + 5000);
                            }
                            return true;
                        }
                        hideBottomLayout();
                        break;
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessage(HIDE);
//                        mHandler.sendEmptyMessage(SHOW);
                        if (recordBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewLeft = getCurrentFocus();
                            if (focusViewLeft != null)
                                if (focusViewLeft.getId() == R.id.seekBar) {
                                    if (player != null) {
                                        player.seekto(player.getCurrentPosition() - 60000);
                                    }
                                    return true;
                                }
                        } else {
                            if (player != null) {
                                player.seekto(player.getCurrentPosition() - 5000);
                            }
                            return true;
                        }
                        hideBottomLayout();
                        break;
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        boolean isflag = false;
                        mHandler.sendEmptyMessage(SHOW);
                        if (recordBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewDown = getCurrentFocus();
                            if (focusViewDown != null)
                                if (focusViewDown.getId() != R.id.seekBar) {
                                    seekBar.requestFocus();
                                    isflag = true;
                                }
                        }
                        /**0925 去掉 改为下面*/
                        hideBottomLayout();
                        return isflag;
                    case KeyEvent.KEYCODE_DPAD_UP:
                        boolean flag = false;
                        if (recordBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewUp = getCurrentFocus();
                            if (focusViewUp != null)
                                if (focusViewUp.getId() == R.id.control_btn) {
                                    seekBar.requestFocus();
                                    flag = true;
                                }
                        } else {
                            mHandler.sendEmptyMessage(SHOW);
                        }
                        hideBottomLayout();
                        return flag;
                    case KeyEvent.KEYCODE_BACK:
                        if ((System.currentTimeMillis() - mExitTime) > 2000) {
                            Toast.makeText(this, "再按一次退出播放", Toast.LENGTH_SHORT).show();
                            mExitTime = System.currentTimeMillis();
                            return true;
                        } else {
                            exit();
                        }
                        return true;
                    case KeyEvent.KEYCODE_HOME:
                        return true;
                }
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private class MyHandler extends Handler {
        private WeakReference<RecordPlayer> reference;

        public MyHandler(RecordPlayer reference) {
            this.reference = new WeakReference<RecordPlayer>(reference);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HIDE:
                    hideSeekbar();
                    break;
                case SHOW:
                    showSeekbar();
                    break;
            }
        }
    }

    private void hideSeekbar() {
        if (player != null) {
            if (player.isPlaying()) {
                recordBottomLayout.setVisibility(View.GONE);
                btn_play_pause.setVisibility(View.GONE);
            }
        }
    }

    private void showSeekbar() {
        recordBottomLayout.setVisibility(View.VISIBLE);
        if (player != null) {
            if (!player.isPlaying()) {
                btn_play_pause.setVisibility(View.VISIBLE);
            }
        }
    }

    protected void exit() {
        mHandler.removeCallbacksAndMessages(null);
        isTimerTask = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (player != null) {
            player.onDestroy();
            player = null;
        }
        Intent intent = new Intent();
        setResult(30002, intent);
        finish();
        overridePendingTransition(0, 0);
    }
}
